package com.example.product.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.product.entity.Account;
import com.example.product.entity.User;
import com.example.product.exception.CustomException;
import com.example.product.mapper.AdminMapper;
import com.example.product.mapper.UserMapper;
import com.example.product.service.UserService;
import com.example.product.util.Result;
import com.example.product.util.TokenUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.function.Function;

/**
 * 用户业务处理
 **/
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AdminMapper adminMapper;

    /**
     * 登录
     */
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    public Result login(Account account) {
        // 对密码进行加密
        String encryptedPassword = SecureUtil.md5(account.getPassword());
        System.out.println("----------------"+account.getPassword());
        System.out.println("----------------"+encryptedPassword);
        logger.info("尝试登录用户: {}", account.getUsername());
        logger.info("角色: {}", account.getRole());
        System.out.println("尝试登录用户: " + account.getUsername());
        System.out.println("角色: " + account.getRole());
        // 根据角色选择查询对应的用户
        if ("ADMIN".equals(account.getRole())) {
            // 查找管理员
            Account admin = adminMapper.selectByUsername(account.getUsername());
            if (admin == null) {
                return new Result(401, "用户名或密码错误，用户不存在", null);
            }
            if (!admin.getPassword().equals(encryptedPassword)) {
                return new Result(401, "用户名或密码错误，密码不匹配", null);
            }
            // 生成 token
            String token = tokenUtil.createToken(admin);
            return new Result(200, "登录成功，返回 token 字符串", token);
        } else {
            // 查找普通用户
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", account.getUsername());
            logger.debug("查询普通用户: {}", account.getUsername());
            User user = userMapper.selectOne(queryWrapper);
            if (user == null) {
                logger.debug("查询普通用户: {}", account.getUsername());
                return new Result(401, "用户名或密码错误，用户不存在", null);
            }
            System.out.println(user.getPassword());
            System.out.println(encryptedPassword);
            if (!user.getPassword().equals(encryptedPassword)) {
                return new Result(401, "用户名或密码错误，密码不匹配", null);
            }
            // 生成 token
            Account userAccount = convertUserToAccount(user);
            String token = tokenUtil.createToken(userAccount);
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("token", token);
            responseData.put("role", user.getRole());
            responseData.put("name", user.getName());
            responseData.put("img", user.getImg());
            responseData.put("username",user.getUsername());
            responseData.put("password",user.getPassword());
            responseData.put("id",user.getId());
            return new Result(200, "登录成功，返回 token 字符串", responseData);

        }
    }


    private Account convertUserToAccount(User user) {
        Account account = new Account();
        account.setId(user.getId());
        account.setUsername(user.getUsername());
        account.setName(user.getName());
        account.setRole(user.getRole());
        account.setImg(user.getImg());
        return account;
    }
    @Override
    /**
     * 新增
     */
    public void add(User user) {
        User dbUser = userMapper.selectByUsername(user.getUsername());
        if (ObjectUtil.isNotNull(dbUser)) {
            throw new CustomException("用户已存在");
        }
        if (ObjectUtil.isEmpty(user.getPassword())) {
            user.setPassword(SecureUtil.md5("123")); // 对默认密码加密
        } else {
            // 对输入的密码进行加密
            user.setPassword(SecureUtil.md5(user.getPassword()));
        }
        if (ObjectUtil.isEmpty(user.getName())) {
            user.setName(user.getUsername());
        }
        user.setRole("USER");
        userMapper.insert(user);
    }
    /**
     * 删除
     */
    @Override
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }
    @Override
    public boolean saveBatch(Collection<User> entityList, int batchSize) {
        return false;
    }
    @Override
    public boolean saveOrUpdateBatch(Collection<User> entityList, int batchSize) {
        return false;
    }

    /**
     * 修改
     */
    @Override
    public boolean updateById(User user) {
        userMapper.updateById(user);
        return false;
    }

    @Override
    public boolean updateBatchById(Collection<User> entityList, int batchSize) {
        return false;
    }
    @Override
    public boolean saveOrUpdate(User entity) {
        return false;
    }
    @Override
    public User getOne(Wrapper<User> queryWrapper, boolean throwEx) {
        return null;
    }
    @Override
    public Optional<User> getOneOpt(Wrapper<User> queryWrapper, boolean throwEx) {
        return Optional.empty();
    }
    @Override
    public Map<String, Object> getMap(Wrapper<User> queryWrapper) {
        return null;
    }
    @Override
    public <V> V getObj(Wrapper<User> queryWrapper, Function<? super Object, V> mapper) {
        return null;
    }
    @Override
    public UserMapper getBaseMapper() {
        return null;
    }
    @Override
    public Class<User> getEntityClass() {
        return null;
    }
    /**
     * 根据ID查询
     */
    @Override
    public User selectById(Integer id) {
        return userMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    @Override
    public List<User> selectAll(User user) {
        return userMapper.selectAll(user);
    }

    /**
     * 分页查询
     */
    @Override
    public PageInfo<User> selectPage(User user, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> list = userMapper.selectAll(user);
        return PageInfo.of(list);
    }

    /**
     * 修改密码
     */
    public void updatePassword(Account account) {
        // 检查输入字段是否为空
        if (StringUtils.isEmpty(account.getUsername()) || StringUtils.isEmpty(account.getPassword())) {
            throw new CustomException("用户名或新密码不能为空");
        }

        // 查询数据库中的用户信息
        User dbUser = userMapper.selectByUsername(account.getUsername());
        if (ObjectUtil.isNull(dbUser)) {
            throw new CustomException("用户不存在");
        }

        // 更新新密码，并保存为加密形式
        dbUser.setPassword(account.getPassword());
        userMapper.updateById(dbUser);
    }



    /**
     * 注册
     * @param user
     */
    @Override
    public void register(User user) {
        this.add(user);
    }
}